package com.zhonghualub.gateway.routeConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

@Slf4j
@Component
public class RouteByNacosListener {
    @Value("${nacos.ip}")
    private String ip;

    @Value("${nacos.port}")
    private String port;

    @Value("${nacos.data-id}")
    private String dataId;

    @Value("${nacos.group}")
    private String group;

    @Value("${nacos.namespace}")
    private String namespace;

    private ConfigService configService;

    @Autowired
    private DynamicRouteServiceImpl dynamicRouteService;

    /**
     * 监听Nacos Server下发的动态路由配置
     */
    public void dynamicRouteByNacosListener (String dataId, String group){
        try {
            // 监听器检测网关的配置变化
            configService.addListener(dataId, group, new Listener()  {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("监听Nacos Server下发的动态路由配置: "+configInfo);
                    List<RouteDefinition> routerList = JSON.parseArray(configInfo, RouteDefinition.class);
                    for (RouteDefinition definition : routerList) {
                        dynamicRouteService.update(definition);
                    }
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        } catch (NacosException e) {
            log.error(e.toString());
        }
    }

    /**
     * 首次初始化路由
     */
    @PostConstruct
    private void initRoute() {
        Properties properties = new Properties();
        properties.setProperty("namespace", namespace);
        properties.setProperty("serverAddr", ip + ":" + port);

        try {
            configService = NacosFactory.createConfigService(properties);
            String configInfo = configService.getConfig(dataId,  group, 5000);
            log.info("拉取初始化网关配置：" + configInfo);
            List<RouteDefinition> definitionList = JSON.parseArray(configInfo, RouteDefinition.class);
            for (RouteDefinition definition : definitionList) {
                log.info("初始化网关配置：" + definition.toString());
                dynamicRouteService.add(definition);
            }
            // 添加监听器
            dynamicRouteByNacosListener(dataId, group);
        }catch (NacosException e) {
            log.error(e.toString());
        }
    }
}
